package com.hucheng.reconciliation.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.hucheng.common.exception.EduException;
import com.hucheng.common.page.PageParameter;
import com.hucheng.common.utils.AlipayUtils;
import com.hucheng.common.utils.TimeUtils;
import com.hucheng.reconciliation.biz.ReconciliationCheckBiz;
import com.hucheng.reconciliation.biz.ReconciliationFileDownBiz;
import com.hucheng.reconciliation.biz.ReconciliationFileParserBiz;
import com.hucheng.reconciliation.config.AliPaySystem;
import com.hucheng.reconciliation.entity.AccountCheckBatchDO;
import com.hucheng.reconciliation.entity.ReconciliationDetailsDO;
import com.hucheng.reconciliation.mapper.AccountCheckBatchMapper;
import com.hucheng.reconciliation.mapper.AlipayOrderMapper;
import com.hucheng.reconciliation.query.AccountCheckBatchQuery;
import com.hucheng.reconciliation.service.AlipayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: 凉白开不加冰
 * @Version: 0.0.1V
 * @Date: 2019-07-26
 * @Description: 订单账目业务
 **/
@Slf4j
@Component
@Service(interfaceClass = AlipayOrderService.class, retries = -1, timeout = 5000)
public class AlipayOrderServiceImpl implements AlipayOrderService {

    @Autowired
    private AliPaySystem aliPaySystem;

    @Autowired
    private ReconciliationFileDownBiz reconciliationFileDownBiz;

    @Autowired
    private AccountCheckBatchMapper accountCheckBatchMapper;

    @Autowired
    private ReconciliationFileParserBiz parserBiz;

    @Autowired
    private ReconciliationCheckBiz reconciliationCheckBiz;

    @Autowired
    private AlipayOrderMapper alipayOrderMapper;

    private ExecutorService service = Executors.newFixedThreadPool(10);

    /**
     * 先下载支付宝账单,并解析
     * signcustomer/trade
     *
     * @throws Exception
     */
    @Override
    public void downloadOrderAccount() throws Exception {

        AlipayClient alipayClient = AlipayUtils.getAlipayClient(aliPaySystem.getAliPay());

        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("bill_type", "trade");
        bizContent.put("bill_date", "2019-01-01");
        request.setBizContent(bizContent.toJSONString());

        String result = alipayClient.execute(request).getBillDownloadUrl();

        String filename = getDownloadFileName(result);

//        String filename = "20881021790657550156_20190101.csv";
//
        String down_url = "F:\\git_workspace\\hucheng-springboot-dubbo\\csv\\" + filename + ".zip";

        //通过调用支付宝接口返回的url下载zip文件
//        boolean down_success = reconciliationFileDownBiz.downLoadBiz(result, down_url);
//        if (down_success) {
//        if (parserBiz.readZipToString(down_url)) {
        log.info("支付宝对账 >>>>>>>>>>> " + "下载支付宝账单并入库成功");
//        }
//        }
    }

    /**
     * 开始对账
     */
    @Override
    public void reconcilicationByDay() {
        service.execute(() -> {
            //每次找处理10条
            int pageSize = 1;
            //当前处理数据
            int curentSize = 1;
            int totalCount = alipayOrderMapper.count(TimeUtils.getSysdate());
            while (curentSize <= totalCount) {
                //查询对账数据
                PageParameter pageParameter = new PageParameter(curentSize, pageSize);
                List<ReconciliationDetailsDO> lists = alipayOrderMapper.list(pageParameter, TimeUtils.getSysdate());
                //生成对账记录
                //生成异常数据对账信息
                //修改对账状态
                System.out.println(lists);
                curentSize++;
            }
        });
    }

    @Override
    public void reconcilicationByMonth() {

    }

    @Override
    @SuppressWarnings("rawtypes")
    public void taskRun() {
        try {

            String dataStr = TimeUtils.findDesignDay(-1, true);

            /** step1:判断是否对过账 **/
            AccountCheckBatchQuery accountCheckBatchQuery = new AccountCheckBatchQuery();
            accountCheckBatchQuery.setBillDate(dataStr);
            accountCheckBatchQuery.setBillType("trade");

            AccountCheckBatchDO accountCheckBatchDO = accountCheckBatchMapper.get(accountCheckBatchQuery);
            if (accountCheckBatchDO != null) {
                throw new EduException("今日已对账");
            }

            /** step2:对账文件下载 **/
            AlipayClient alipayClient = AlipayUtils.getAlipayClient(aliPaySystem.getAliPay());
            AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
            JSONObject bizContent = new JSONObject();
            bizContent.put("bill_type", "trade");
            bizContent.put("bill_date", dataStr);
            request.setBizContent(bizContent.toJSONString());
            String result = alipayClient.execute(request).getBillDownloadUrl();
            String filename = getDownloadFileName(result);
            String downUrl = "F:\\git_workspace\\hucheng-springboot-dubbo\\csv\\" + filename + ".zip";
            boolean flag = reconciliationFileDownBiz.downLoadBiz(result, downUrl);
            if (!flag) {
                throw new EduException("下载文件出错");
            }

            /** step3:解析对账文件 **/
            flag = parserBiz.parser(downUrl);
            if (!flag) {
                throw new EduException("解析入库账单失败");
            }

            /** step4:对账流程 **/
            reconciliationCheckBiz.checkBiz(dataStr);


        } catch (Exception e) {
            log.error("dubbo-reconciliation-provider error:", e);
        }
    }

    /**
     * 通过alipay_url获取下载的文件名称
     *
     * @param alipay_url
     * @return
     */
    private static String getDownloadFileName(String alipay_url) {
        String tempStr = alipay_url.substring(alipay_url.indexOf("downloadFileName") + 17, alipay_url.length());
        tempStr = tempStr.substring(0, tempStr.indexOf(".zip"));
        return tempStr;
    }


//    /**
//     * 解压缩
//     * 解压通过url获得对账单数据流（.zip）
//     *
//     * @param file //zip文件存放地址
//     * @return
//     */
//    @SuppressWarnings("unchecked")
//    public static String comZipCvsFile(File file) throws Exception {
//        //自定义文件保存地址
//        String unzipFilePath = file.getCanonicalPath();
//        unzipFilePath = unzipFilePath.substring(0, unzipFilePath.lastIndexOf("."));
//        System.out.println("解压后文件保存路径：" + unzipFilePath);
//
//        //获得输入流，文件为zip格式，
//        //支付宝提供
//        //20886126836996110156_20160906.csv.zip内包含
//        //20886126836996110156_20160906_业务明细.csv
//        //20886126836996110156_20160906_业务明细(汇总).csv
//        ZipInputStream in = new ZipInputStream(new FileInputStream(file));
//
//        ZipInputStream zin = new ZipInputStream(in);
//        ZipEntry zipFile;
//        BufferedOutputStream bos = null;
//        try {
//
//            zin = new ZipInputStream(new FileInputStream(file));
//
//            while ((zipFile = zin.getNextEntry()) != null) {
//                System.out.println(zipFile.getName());
//
//                File target = new File(file.getParent(), zipFile.getName());
//
//                if (!target.getParentFile().exists()) {
//                    // 创建文件父目录
//                    target.getParentFile().mkdirs();
//                }
//
//                //创建解压缩文件保存的路径 文件夹
//                //解压文件存放地址---unzipFilePath(解压文件去吃.zip)
//                File unzipFileDir = new File(unzipFilePath);
//                if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
//                    unzipFileDir.mkdirs();
//                }
//
//
//                String file_Name_csv = target.getName();
//                //decom_Path(存放地址)+文件名
//                String entryFilePath = unzipFilePath + File.separator + file_Name_csv;
//
//                //解压文件是否已存在
//                File entryFile = new File(entryFilePath);
//                if (entryFile.exists()) {
//                    //删除已存在的目标文件
//                    entryFile.delete();
//                }
//
//                /*
//                 * 写入文件，解压到和zip在同一个文件夹
//                 */
////              bos = new BufferedOutputStream(new FileOutputStream(target));
//                //自定义文件夹
//                bos = new BufferedOutputStream(new FileOutputStream(entryFile));
//
//                int read = 0;
//                byte[] buffer = new byte[1024 * 10];
//
//                while ((read = zin.read(buffer, 0, buffer.length)) != -1) {
//                    bos.write(buffer, 0, read);
//                }
//
//                bos.flush();
//            }
//            //关闭流
//            zin.close();
//            bos.close();
//
//        } catch (Exception e) {
//            // TODO: handle exception
//            System.out.println("zip文件解压失敗" + e);
//
//            return "false";
//        }
//        //返回解压文件保存路径
//        return unzipFilePath;
//
//    }


//    /**
//     * 读取zip文件，不解压缩直接解析，支持文件名中文，解决内容乱码
//     *
//     * @param file
//     * @return 读取zip文件，返回字符串
//     * @throws Exception
//     */
//    @SuppressWarnings("unchecked")
//    public static String readZipToString(File file) throws Exception {
//        String connet = "";
//        try {
//            //获得输入流，文件为zip格式，
//            //支付宝提供
//            //20886126836996110156_20160906.csv.zip内包含
//            //20886126836996110156_20160906_业务明细.csv
//            //20886126836996110156_20160906_业务明细(汇总).csv
//            ZipInputStream in = new ZipInputStream(new FileInputStream(file));
//            //不解压直接读取,加上gbk解决乱码问题
//            BufferedReader br = new BufferedReader(new InputStreamReader(in, "gbk"));
//            ZipEntry zipFile;
//            //返回的字符串---每个文件内容相加
//            BufferedWriter bw = null;
//            //循环读取zip中的cvs文件，无法使用jdk自带，因为文件名中有中文
//            while ((zipFile = in.getNextEntry()) != null) {
//                if (zipFile.isDirectory()) {
//                    //如果是目录，不处理
//                }
//                String file_connet = "";
//                //获得cvs名字
//                String fileName = zipFile.getName();
//                System.out.println("-----" + fileName);
//                //检测文件是否存在
//                if (fileName != null && fileName.indexOf(".") != -1) {
//                    String line;
//                    /*
//                     * 1.每一行用 | 隔开
//                     * 2.每一个文件用 ; 隔开
//                     */
//                    //  bw = new BufferedWriter(new FileWriter("d:\\test\\test.txt")); //测试读取内容
//                    while ((line = br.readLine()) != null) {
//
//                        file_connet = file_connet + "|" + line;
//                        // System.out.println(line);
//
//                    }
//                }
//
//                connet = connet + file_connet + ";";
//            }
//            //  bw.write(connet);
//            //关闭流
//            //  bw.close();
//            br.close();
//            in.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "false";
//        }
//
//        return connet;
//    }

}
